from datetime import datetime

from sqlalchemy import Table, ForeignKey, Column, Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relation, backref

from papyrus.model.meta import Base

# many-to-many relation between users and groups
users_groups = Table('users_groups', Base.metadata,
    Column('user_id', None, ForeignKey('users.id')),
    Column('group_id', None, ForeignKey('groups.id')),
)

# many-to-many relation between permissions and users
permissions_users = Table('permissions_users', Base.metadata,
    Column('permission_id', None, ForeignKey('permissions.id')),
    Column('user_id', None, ForeignKey('users.id')),
)

# many-to-many relation between permissions and groups
permissions_groups = Table('permissions_groups', Base.metadata,
    Column('permission_id', None, ForeignKey('permissions.id')),
    Column('group_id', None, ForeignKey('groups.id')),
)


class User(Base):
    """A user object."""

    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    email = Column(Unicode, nullable=False, unique=True)
    name = Column(Unicode, nullable=False)
    password = Column(Unicode, nullable=False)
    confirmed = Column(Boolean, default=False, nullable=False)
    is_admin = Column(Boolean, default=False, nullable=False)
    creation_date = Column(DateTime, default=datetime.now)

    articles = relation('Article', backref="author", order_by='Article.creation_date', cascade="all, delete-orphan")

    def __repr__(self):
        return "<%s %r, %r>" % (self.__class__.__name__, self.id, self.email)


class Group(Base):
    """A group object."""

    __tablename__ = 'groups'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode, nullable=False, unique=True)

    users = relation('User', backref="groups", order_by=None, secondary=users_groups)

    def __repr__(self):
        return "<%s %r, %r>" % (self.__class__.__name__, self.id, self.name)


class Permission(Base):
    """A permission object."""

    __tablename__ = 'permissions'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode, nullable=False, unique=True)

    users = relation('User', backref="permissions", order_by=None, secondary=permissions_users)
    groups = relation('Group', backref="permissions", order_by=None, secondary=permissions_groups)

    def __repr__(self):
        return "<%s %r, %r>" % (self.__class__.__name__, self.id, self.name)
